package com.bigknow.appstore.proxy.server.impl;

import com.bigknow.appstore.proxy.handler.base.BaseInboundHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpMessage;
import io.netty.handler.codec.http.FullHttpResponse;

import java.net.InetSocketAddress;

/**
 * Created by chaos on 2016/9/14.
 */
public class  ProxyTarget extends BaseInboundHandler {

    private HttpChannelProxyToServer ps;

    public ProxyTarget(HttpChannelProxyToServer httpChannelProxyToServer) {
        super(httpChannelProxyToServer.getProxyServer(),
                httpChannelProxyToServer.getCacheManager(),
                httpChannelProxyToServer.getWriter());
        this.ps = httpChannelProxyToServer;
    }

    @Override
    public void read(ChannelHandlerContext ctx, FullHttpMessage msg) throws Exception {
        if (msg instanceof FullHttpResponse) {

            if (!ps.getProxyChannel().isActive()) {
                //TODO://这里要记录日志
                return;
            }

            ps.getProxyChannel().writeAndFlush(msg).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ps.disConnect();
                        //TODO://这里需要记录日志
                    }
                }
            });
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        logger.debug("连接已经超时或者异常断开，信息：" + cause.getMessage());
    }
}
